/**
 * Simple MediaWiki JS Client, @see html/demo/index.html for real life example!
 * 
 * @author Adrian 'ADi' Wieczorek
 * @version 1.0
 * 
 * this addon requires:
 * 
 * - jQuery (1.4.2 or higher)
 * - jQuery UI (1.8.4 or higher)
 * - optional: jQuery loading plugin (1.6 4 or higher)
 * 
 * 
 * @todo same page links support
 */
MediaWikiBrowser = function(wikiUrl, width, height) {
	var date = new Date;
	this.panelId = 'mwBrowserId'+date.getTime();

	// this line is an optional, and requires jQuery Loading plugin
	// $.loading({onAjax:true, delay: 100});

	this.client = new MediaWikiClient(wikiUrl);
	this.panel = $('<div id="'+this.panelId+'"></div>').dialog({ autoOpen: false });

	this.panel.dialog('option', 'width', width);
	this.panel.dialog('option', 'height', height);

	this.panelMsg = $('<div id="'+this.panelId+'MsgPanel"></div>').dialog({ 
		autoOpen: false,
		modal: true, 
		buttons: {
			Ok: function() { $(this).dialog('close'); }
		}
	});
	this.panelMsg.dialog('option', 'width', 400);
	this.panelMsg.dialog('option', 'title', 'Error');
	
	this.history = [];
	this.historyIndex = -1;
};

MediaWikiBrowser.prototype.open = function (articleTitle, skipHistoryUpdate) {
	var browser = this;

	var successCallback = function(data) {
		if( skipHistoryUpdate != true) {
			updateHistory(articleTitle);
		}

		browser.panel.dialog('option', 'title', renderNavbar(articleTitle));
		browser.panel.html('<div id="'+browser.panelId+'ArticleContent">'+data+'</div>');
		browser.panel.dialog('open');
		hijackLinks();

		/*
		$('ul#'+browser.panelId+'NavIcons li.ui-corner-all').hover(
			function() { $(this).addClass('ui-state-hover'); }, 
			function() { $(this).removeClass('ui-state-hover'); }
		);
		*/

		var nextBtn = $('#'+browser.panelId+'NextButton');
		var prevBtn = $('#'+browser.panelId+'PrevButton');
		var titleGoBtn = $('#'+browser.panelId+'TitleGoButton');
		var titleInput = $('#'+browser.panelId+'TitleInputBar');

		updateButtons( titleGoBtn, nextBtn, prevBtn );

		titleInput.bind( 'keypress', function(event) {
			var newTitle = $(this).val();
			if( ( event.keyCode == '13' ) && ( newTitle != '' ) ) {
				browser.open(newTitle);
			}
		});

		titleInput.bind( 'keyup', function(event) { 
			var newTitle = $(this).val();
			if( newTitle != '') {
				titleGoBtn.addClass('ui-state-active');
				titleGoBtn.removeClass('ui-state-default');
			}
			else {
				titleGoBtn.addClass('ui-state-default');
				titleGoBtn.removeClass('ui-state-active');
			}
		});

		titleGoBtn.bind( 'click', function() {
			var newTitle = $('#'+browser.panelId+'TitleInputBar').val();
			if( newTitle != '' ) {
				browser.open(newTitle);
			}
		});

		prevBtn.bind( 'click', goPrevPage );
		nextBtn.bind( 'click', goNextPage );
	};

	var errorCallback = function(XMLHttpRequest, textStatus, errorThrown) {
		browser.panelMsg.html("Article \""+articleTitle+"\" doesn't exists.");
		browser.panelMsg.dialog('open');
	};

	this.client.getArticle(articleTitle, successCallback, errorCallback);

	var renderNavbar = function(title) {
		var body = '';

		body += '<ul id="'+browser.panelId+'NavIcons" class="mwBrowserNavIcons ui-widget ui-helper-clearfix">';
		body += '<li id="'+browser.panelId+'PrevButton" class="ui-state-default ui-corner-all" title="back"><span class="ui-icon ui-icon-circle-arrow-w"></span></li>';
		body += '<li id="'+browser.panelId+'NextButton" class="ui-state-default ui-corner-all" title="forward"><span class="ui-icon ui-icon-circle-arrow-e"></span></li>';
		body += '<li class="mwBrowserTitleInputBar">';
		body += '<input type="text" id="'+browser.panelId+'TitleInputBar" class="mwBrowserTitleInputBar" value="'+title+'" />';
		body += '</li><li>'
		body += '<li id="'+browser.panelId+'TitleGoButton" class="ui-state-default ui-corner-all" title="forward"><span class="mwBrowserTitleGoButtonText">Go</span></li>';
		body += '</li></ul>';

		return body;
	};

	var hijackLinks = function() {
		$('#'+browser.panelId+'ArticleContent').delegate('a', 'click', function(e) { 
			e.preventDefault();
			var cl = $(this).attr('class');
			var href = $(this).attr('href');
			if( cl == 'new' ) {
				browser.panelMsg.html("This article doesn't exists yet. Editing not supported.");
				browser.panelMsg.dialog('open');
			}
			else {
				var title = $(this).attr('title');
				browser.open(title);
			}
		});
	};

	var updateHistory = function(title) {
		browser.historyIndex++;
		browser.history[browser.historyIndex] = title;
		//console.log(browser.history);
		//console.log(browser.historyIndex);
	};

	var updateButtons = function( titleGoBtn, nextBtn, prevBtn ) {
		titleGoBtn.addClass('ui-state-active');
		titleGoBtn.removeClass('ui-state-default');
		if( browser.historyIndex < browser.history.length-1 ) {
			nextBtn.addClass('ui-state-active');
			nextBtn.removeClass('ui-state-default');
		}
		if( browser.historyIndex > 0 ) {
			prevBtn.addClass('ui-state-active');
			prevBtn.removeClass('ui-state-default');
		}
	};

	var goPrevPage = function() {
		if( browser.historyIndex > 0 ) {
			browser.historyIndex--;
			browser.open(browser.history[browser.historyIndex], true);
		}
	};

	var goNextPage = function() {
		if( browser.historyIndex < browser.history.length-1 ) {
			browser.historyIndex++;
			browser.open(browser.history[browser.historyIndex], true);
		}
	};
};

MediaWikiClient = function(wikiUrl) {
	this.wikiUrl = wikiUrl;
};

MediaWikiClient.prototype.getArticle = function (title, callback, errorCallback) {
	var urlParams = {
		'action' :'render',
		'title' : title
	};

	return jQuery.ajax({
		url: this.wikiUrl,
		data: urlParams,
		success: callback,
		error: errorCallback,
	});
};
